<template>
  <info-page-container @goListPage="cancel">
    <div class="info-data-container full-container flex-column">


      <div class="info-base-data">
        <el-form :rules="rules" :model="dataItem" ref="baseForm" size="small"
                 label-width="80px">
          <el-form-item label="农户编号" prop="farmerNo">
            <el-input
              v-model="dataItem.farmerNo"
              placeholder="请输入农户编号"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="农户名称" prop="farmerName">
            <el-input
              v-model="dataItem.farmerName"
              placeholder="请输入农户名称"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="性别" prop="farmerSex">
            <el-select v-model="dataItem.farmerSex" placeholder="请选择">
              <el-option
                v-for="item in SEX_LIST"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" prop="farmerAge">
            <el-input
              type="number"
              v-model="dataItem.farmerAge"
              placeholder="请输入年龄"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="farmerIdentity">
            <el-input
              v-model="dataItem.farmerIdentity"
              placeholder="请输入身份证号"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <div class="list-container">
        <layout-container title="地块列表">
          <template slot="title">
            <div class="important-txt" style="margin-left: 20px">
              总面积：{{sumArea}} 亩
            </div>
          </template>
          <template slot="bt">
            <el-button class="diy-bt txt-bt" icon="el-icon-plus" size="mini" @click="addPlot">
              新增地块
            </el-button>
          </template>
          <template>
            <el-table
              class="diy-table"
              :data="dataItem.farmerPlots"
              style="width: 100%;" height="100%">
              <el-table-column
                prop="plotNo"
                label="编号">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.plotNo"
                    placeholder="请输入地块编号"
                    clearable
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="geometryArea"
                label="面积（亩）">
              </el-table-column>

              <el-table-column width="150" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="locationByData(plotLayerId,scope.row,'地块信息')"
                  >定位
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="removePlot(scope.row)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>

            </el-table>
          </template>
        </layout-container>
      </div>

      <div class="handle-bt-container flex-row">
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="save">保存</el-button>
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="cancel">取消</el-button>
      </div>

    </div>
  </info-page-container>
</template>

<script>
import {infoPageMixins} from "@/views/business/mixins/infoPageMixins";
import {pageBaseMapMixins} from "@/views/business/mixins/pageBaseMapMixins";
import {GET_LOCATE_SYMBOL} from "@/utils/SymbolUtils";
import {addFarmer, getFarmerInfo, updateFarmer} from "@/api/business/userManagement";
import {GEOMETRY_TYPE, HANDLE_TYPE, REFRESH_PAGE_TYPE, SEX_LIST} from "@/views/business/constantData";
import guid from "@/utils/guid";
import {isArr} from "@/utils/arrayUtil";

export default {
  mixins: [infoPageMixins, pageBaseMapMixins],
  data() {
    return {
      SEX_LIST,
      plotLayerId: 'plot',
      sumArea: 0,
      farmerPlotId: 'farmerPlotId',
      rules: {
        farmerName: [
          {required: true, message: '农户名称不能为空', trigger: 'blur'},
        ]
      },
      currentHandleType: '',
    }
  },
  methods: {
    cancel() {
      this.removeFarmerLayer()
      this.goListPage(REFRESH_PAGE_TYPE.REFRESH)
    },
    saveFinish() {
      this.removeFarmerLayer()
      this.goListPage(REFRESH_PAGE_TYPE.REFRESH)
    },
    removeFarmerLayer() {
      this.removeRender()
      this.removeLayer({layerId: this.plotLayerId})
    },
    //  设置当前数据
    setCurrentItem(currentItem) {
      this.startLoading()
      this.removeRender()
      let owner = this
      if (currentItem != null && currentItem?.id != null && currentItem?.id !== '') {
        this.currentHandleType = HANDLE_TYPE.UPDATE
        getFarmerInfo(currentItem).then(res => {
          res.data.farmerPlots = res.data.farmerPlots.map(item => {
            item.geoData = JSON.parse(item.geoData)
            return item
          })
          owner.dataItem = res.data
          owner.heightCurrentFarmerPlot(owner.dataItem.id)
        }).finally(() => {
          owner.endLoading()
        });
      } else {
        this.currentHandleType = HANDLE_TYPE.ADD
        owner.dataItem = {
          //  年龄
          farmerAge: null,
          //  身份证
          farmerIdentity: null,
          //  农户名称
          farmerName: null,
          //  农户编号
          farmerNo: null,
          //  地块数据
          farmerPlots: [],
          //  性别0女1男
          farmerSex: null,
        };
        owner.endLoading();
      }
    },

    async heightCurrentFarmerPlot(farmerId) {
      let owner = this
      return new Promise(async (resolve, reject) => {
        const where = `farmerId = '${farmerId}'`
        let currentFarmerFeatures = await owner.getGraphicByGeometryAndWhere({layerId: owner.farmerPlotId, where});
        if (isArr(currentFarmerFeatures)) {
          await this.addFarmerLayer(currentFarmerFeatures)
        }
        resolve()
      })
    },

    async addFarmerLayer(source) {
      let owner = this
      return new Promise(async (resolve, reject) => {
        const geometryType = GEOMETRY_TYPE.POLYGON;
        const txtFileList = [{
          value: this.areaFiled,
          label: '面积',
          suffix: ' 亩'
        }]

        if (owner.currentHandleType == HANDLE_TYPE.UPDATE) {
          txtFileList.unshift({
            value: 'plotNo',
            label: '地块编号',
          })
          txtFileList.unshift({
            value: 'farmerName',
            label: '农户名称',
          })
        }
        await owner.addLayer({
          layerId: owner.plotLayerId,
          source,
          rendererSymbol: GET_LOCATE_SYMBOL(geometryType),
          geometryType,
          txtFileList,
          txtColor: '#000',
          fontSize: 15
        })
        owner.sumArea = await this.getSumAreaByLayerIdAndQueryParam({layerId: this.plotLayerId});
        resolve()
      })
    },

    save() {
      let owner = this
      this.$refs.baseForm.validate((valid) => {
        if (valid) {
          owner.startLoading()
          let {dataItem: {id}} = owner
          this.dataItem.farmerPlots = _.map(this.dataItem.farmerPlots, item => {
            let {geoData, plotNo, geometryArea} = item
            return {geoData: JSON.stringify(geoData), plotNo, geometryArea}
          })
          if (id == null || id == '') {
            addFarmer(this.dataItem).then(res => {
              this.$message({
                message: '添加成功',
                type: 'info'
              })
            }).finally(() => {
              owner.endLoading()
              this.saveFinish()
            })
          } else {
            updateFarmer(this.dataItem).then(res => {
              this.$message({
                message: '修改成功',
                type: 'info'
              })
            }).finally(() => {
              owner.endLoading()
              this.saveFinish()
            })
          }
        }
      });
    },
    async addPlot() {
      this.$message({
        message: '请在左侧地图进行绘制',
        type: 'info'
      })
      const geometryType = GEOMETRY_TYPE.POLYGON;
      let graphic = await this.baseMap.drawGeometry(geometryType, true);
      let coincideFlag1 = await this.baseMap.checkCoincideByGraphic({layerId: this.plotLayerId, graphic})
      let coincideFlag = await this.baseMap.checkCoincideByGraphic({layerId: this.farmerPlotId, graphic})
      if (coincideFlag || coincideFlag1) {
        this.$message.error(`绘制地块不能重合`);
        return
      }
      graphic.attributes = {
        id: `id${guid()}`,
        plotNo: null
      };

      if (this.currentHandleType == HANDLE_TYPE.UPDATE) {
        graphic.attributes.farmerName = this.dataItem.farmerName
      }
      this.setAreaToFeatures([graphic]);
      await this.addFarmerLayer([graphic])
      this.addDataToDataItem(graphic)
    },

    async removePlot(plotItem) {
      this.startLoading()
      let {id} = plotItem;
      const where = `id = '${id}'`
      await this.delFeaturesByGeometryAndWhere({layerId: this.plotLayerId, where})
      await this.delFeaturesByGeometryAndWhere({layerId: this.farmerPlotId, where});
      this.removeRender()

      this.dataItem.farmerPlots = this.dataItem.farmerPlots.filter(item => item.id != plotItem.id)
      this.sumArea = await this.getSumAreaByLayerIdAndQueryParam({layerId: this.plotLayerId});

      this.endLoading()
    },
    locationByData(layerId, row, popupTitle) {
      let {id} = row
      const where = `id = '${id}'`
      this.locationByWhere({layerId, where, openPopupFlag: true, popupTitle})
    },
    addDataToDataItem(graphic) {
      let {attributes, geometry: {rings: geoData}} = graphic;
      this.dataItem.farmerPlots.push({...attributes, geoData})
    },
  },
};
</script>

<style scoped lang="scss">
.info-data-container{
  .info-base-data{
    height: 35% !important;
    max-height:  35% !important;
  }
  .list-container{
    height: 58% !important;
  }
  .handle-bt-container{}
}
</style>
